<template>
  <div>
    <el-dialog title="添加分类" :visible="showDialog" @close="empty">
      <el-form ref="form" :model="formDate" :rules="rules" label-width="80px">
        <el-form-item prop="title" label="标题">
          <el-input v-model="formDate.title" />
        </el-form-item>
        <el-form-item prop="desc" label="描述">
          <el-input v-model="formDate.desc" />
        </el-form-item>
        <el-form-item label="封面">
          <upload ref="uploadImg1" />
        </el-form-item>
        <el-row type="flex" justify="center">
          <el-form-item>
            <el-button type="primary" @click="addFn">确定</el-button>
            <el-button @click="empty">取消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { addClass, EditClass, getEditDate } from '@/api/classify'
import upload from '@/components/Uploadimgin'
export default {
  components: {
    upload
  },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formDate: {
        title: '',
        desc: '', // 描述,
        image: ''
      },
      rules: {
        title: [{ required: true, message: '该项不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '该项不能为空', trigger: 'blur' }]
      }

    }
  },
  methods: {
    // 点击确定
    async addFn() {
      //  1校验
      await this.$refs.form.validate()
      // console.log(this.formDate)
      if (this.formDate.id) {
        // 有id说明在编辑
        // 调用接口
        this.formDate.image = this.$refs.uploadImg1.fileList[0].url
        await EditClass(this.formDate)
      } else {
        if (this.$refs.uploadImg1.fileList) {
          this.formDate.image = this.$refs.uploadImg1.fileList[0].url
        }
        // 调用接口'
        await addClass(this.formDate)
      }
      this.empty()
      // 渲染页面 粉丝事件 父组件监听事件 然后调用渲染函数
      this.$emit('updateEvent')
    },
    // 获取数据回显
    async  getEditDates(id) {
      const res = await getEditDate(id)
      this.formDate = res.data
      // 实现头像回显
      if (this.formDate.image) {
        // console.log('进来了')
        this.$refs.uploadImg1.fileList.push({
          url: this.formDate.image
        })
      }
    },

    // 封装一个关闭弹框清空数据的函数
    empty() {
      this.$emit('closeEvent', false)
      // 清空数据
      this.formDate = {
        title: '',
        describe: '' // 描述,
      }
      // 清空头像
      this.$refs.uploadImg1.fileList = []
      // 清空校验
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style>

</style>
